package com.itheima.web.servlet;

import com.itheima.domain.User;
import com.itheima.service.ServiceIml;
import com.itheima.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            //设置编码
            request.setCharacterEncoding("utf-8");
            //获取所有数据
            Map<String, String[]> parameterMap = request.getParameterMap();

            //封装对象
            User user = new User();
            BeanUtils.populate(user,parameterMap);

            //调用service中方法
            UserService service=new ServiceIml();
            service.addUser(user);


            //跳转到userListServlet，再次查询
            response.sendRedirect(request.getContextPath()+"/userListServlet");

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
